#include <brpc/channel.h>
#include <thread>
#include "main.pb.h"

void callback(brpc::Controller *cntl, example::EchoResponse *response)
{
    std::unique_ptr<brpc::Controller> cntl_guard(cntl);
    std::unique_ptr<example::EchoResponse> resp_guard(response);

    if (cntl->Failed() == true)
    {
        std::cout << "发起RPC请求失败: " << cntl->ErrorText() << std::endl;
        return;
    }
    std::cout << "收到响应: " << response->message() << std::endl;
}

int main(int argc, char *argv[])
{
    // 构造Channel信道,连接服务器
    brpc::ChannelOptions options;
    // 请求连接超时时间
    options.connect_timeout_ms = -1;
    // brpc超时时间
    options.timeout_ms = -1;
    // 最大重试次数
    options.max_retry = 3;
    // 序列化协议类型
    options.protocol = "baidu_std";

    brpc::Channel channel;
    int ret = channel.Init("127.0.0.1:8080", &options);
    if (ret == -1)
    {
        std::cout << "信道初始化失败" << std::endl;
        return -1;
    }

    // 构造EchoService_Stub对象,用于进行rpc调用
    example::EchoService_Stub echo_stub(&channel);
    // 进行Rpc调用
    example::EchoRequest req;
    req.set_message("Hello EchoService");

    brpc::Controller *cntl = new brpc::Controller();
    example::EchoResponse *rsp = new example::EchoResponse();

    // 同步调用
    echo_stub.Echo(cntl, &req, rsp, nullptr);
    if (cntl->Failed() == true)
    {
        std::cout << "发起RPC请求失败: " << cntl->ErrorText() << std::endl;
        return -1;
    }

    std::cout << "收到响应: " << rsp->message() << std::endl;
    delete cntl;
    delete rsp;

    // 异步调用
    // google::protobuf::Closure *closure = google::protobuf::NewCallback(callback, cntl, rsp);
    // echo_stub.Echo(cntl, &req, rsp, closure);

    // std::cout << "RPC异步调用结束 " << std::endl;
    // std::this_thread::sleep_for(std::chrono::seconds(3));
    return 0;
}